package com.dayu.finecomm.iot.service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dayu.finecomm.iot.IotConsole;
import com.dayu.finecomm.iot.params.IotPlatParam;
import com.dayu.finecomm.mongo.pojo.IotPlat;
import com.dayu.finecomm.mongo.service.IotPlatService;

/**
 * IotPlatDamon, 定时刷新Refresh Token
 * @author XuJialiang
 * @since 2017-09-04 10:22:12
 * @version V1.0.0
 */
public class IotPlatDamon implements Runnable {
	static Logger LOGGER = LoggerFactory.getLogger(IotPlatDamon.class);
	
	/**
	 * IOT Plat 数据库
	 */
	private IotPlatService mMongoDB;
	
	/**
	 * Refresh Token 间隔时间
	 */
	private long mRefreshInterval;
	
	public IotPlatDamon(IotPlatService mongoDB) {
		this(mongoDB, 1800);
	}

	public IotPlatDamon(IotPlatService mongoDB, int interval) {
		mMongoDB = mongoDB;
		
		mRefreshInterval = interval * 1000;
		
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.scheduleAtFixedRate(this, 10, 600, TimeUnit.SECONDS);
	}
	
	/**
	 * 刷新RefreshToken
	 */
	public void run() {
		List<IotPlat> list = mMongoDB.queryAll();
		
		Iterator<IotPlat> it = list.iterator();
		while(it.hasNext()) {
			IotPlat iotPlat = (IotPlat)it.next();
			
			long lastTime = iotPlat.getRefreshTime();
			long curTime = new Date().getTime();
			
			if (curTime - lastTime >= mRefreshInterval) {
				IotPlatParam record = new IotPlatParam();
				record.appid = iotPlat.getAppId();
				record.secret = iotPlat.getSecret();
				record.service = iotPlat.getService();
				record.token = iotPlat.getAccessToken();
				record.refreshToken = iotPlat.getRefreshToken();
				record.protocol = iotPlat.getProtocol();
				
				LOGGER.info("Runnable Refresh Token: " + record.appid);
				
				String result = IotConsole.getInstance().handleIotRefreshToken(record);
				
				JSONObject json = JSON.parseObject(result);
				int code = json.getIntValue("Code");
				if (0 != code) {
					LOGGER.info("Runnable Auth: " + record.appid);
					
					IotConsole.getInstance().handleIotAuth(record);
				}
			}
		}
	}
}
